using System;
using System.IO;
using SubSonic.Utilities;

namespace SubSonic
{
    public class ResourceHelper
    {
        /// <summary>
        /// Loads a template given a resource name. If the TemplateDirectory parameter is set in Web.config,
        /// it will attempt to load the template by file name. If this TemplateDirectory value is empty,
        /// it will attempt to load the template by resource name in the Resources.resx file. 
        /// </summary>
        /// <param name="resourceName"></param>
        /// <returns></returns>
        public static string GetString(string resourceName)
        {
            if (SubSonicConfig.TemplateDirectory != String.Empty && File.Exists(Path.Combine(SubSonicConfig.TemplateDirectory, resourceName + ".txt")))
            {
                return GetTemplateFromFile(resourceName);
            }
            else
            {
                return GetTemplateFromResource(resourceName);
            }
        }

        /// <summary>
        /// Loads a template from a .txt file
        /// </summary>
        /// <param name="fileName">The name of file (WITHOUT the .txt extension)</param>
        /// <returns></returns>
        public static string GetTemplateFromFile(string fileName)
        {
            string result;
            string templateDirectory = SubSonicConfig.TemplateDirectory;
            if (!Directory.Exists(templateDirectory))
            {
                throw new Exception("Can't find the template directory: " + templateDirectory);
            }
            //the template we're looking for should be named the same as the Resource, but with a "txt" extension
            string filePath = Path.Combine(templateDirectory, fileName + ".txt");
            if (File.Exists(filePath))
            {
                result = Utility.GetFileText(filePath);
            }
            else
            {
                throw new Exception("Can't find the template: " + filePath);
            }
            return result;
        }

        /// <summary>
        /// Loads a template from the Resources.resx file
        /// </summary>
        /// <param name="resourceName">The name of the resource to load</param>
        /// <returns></returns>
        public static string GetTemplateFromResource(string resourceName)
        {
            return Properties.Resources.ResourceManager.GetString(resourceName);
        }
    }
}
